import React, { Component } from 'react';

export function createForm(Com) {
    return class extends Component {
        constructor(props) {
            super(props)
            this.state = {}
            this.options = {}
        }
        handleChange = (e) => {
            const { name, value } = e.target
            this.setState({ [name]: value })
        }
        getFieldDecorator = (fieldName, option) => InputCom => {
            this.options[fieldName] = option?.rules || []
            return React.cloneElement(InputCom, {
                value: this.state[fieldName],
                onChange: this.handleChange,
                name: fieldName
            })
        }
        getFieldValue = (name) => {
            return this.state[name]
        }
        getFieldsValue = () => {
            return { ...this.state }
        }
        setFieldsValue = stores => {
            console.log('~~setFieldsValue',stores)
            this.setState(stores)
        }
        validateFields = callback => {
            let err = []
            // console.log('~~this.option', this.options)
            let options = this.options
            for (let fieldName in options) {
                options[fieldName].forEach(rule => {
                    if (rule.require === true && !this.state[fieldName]) {
                        err.push({ [fieldName]: rule.message })
                    }
                    if(rule.minLength&&this.state[fieldName]?.length<3){
                        err.push({ [fieldName]: rule.message })
                    }
                })
            }
            callback(err.length ? err : null, this.state)
        }
        getForm() {
            return {
                getFieldDecorator: this.getFieldDecorator,
                getFieldValue: this.getFieldValue,
                getFieldsValue: this.getFieldsValue,
                setFieldsValue: this.setFieldsValue,
                validateFields: this.validateFields
            }
        }
        render() {
            const form = this.getForm()
            return <Com {...this.props} form={form} />
        }
    }
}
